package com.ytd.common.util;

import com.ytd.common.bean.response.UploadLogResponse;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class UplogUtils {
    private static final String TAG = "uploadFile";
    public static final String NOT_FOUND = "not found";
    private static final int TIME_OUT = 10 * 1000; // 超时时间

    /**
     * @param url 提交的url路径
     * @param params 提交的表单参数.
     * @return String
     */
    public static String doPostSubmitBody(String url, Map<String, String> params, File file) {
        LogUtil.e(TAG, "doPostSubmitBody : " + url + "  file:" + file.getName());
        String newLine = "\r\n";
        String prefix = "--";
        String boundary = "#";
        HttpURLConnection httpConn = null;
        DataOutputStream dos = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            URL urlObj = new URL(url);
            httpConn = (HttpURLConnection) urlObj.openConnection();
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            httpConn.setUseCaches(false);
            httpConn.setReadTimeout(TIME_OUT);
            httpConn.setRequestMethod("POST");
            // 设置HTTP请求的头文件
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            httpConn.setRequestProperty("Cache-Control", "no-cache");
            httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            httpConn.connect();
            // 提交表单信息
            dos = new DataOutputStream(httpConn.getOutputStream());
            if (params != null && !params.isEmpty()) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String key = entry.getKey();
                    String value = params.get(key);
                    dos.writeBytes(prefix + boundary + newLine);
                    dos.writeBytes("Content-Disposition: form-data; " + "name=\"" + key + "\"" + newLine);
                    dos.writeBytes(newLine);
                    dos.write(value.getBytes(StandardCharsets.UTF_8));
                    dos.writeBytes(newLine);
                }
            }

            dos.writeBytes(prefix + boundary + newLine);
            String fileName = file.getName();
            dos.writeBytes(
                "Content-Disposition: form-data; " + "name=\"" + "file" + "\"" + "; filename=\"" + fileName + "\"" +
                    newLine);
            dos.writeBytes(newLine);
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            is.close();
            dos.writeBytes(newLine);
            dos.writeBytes(prefix + boundary + prefix + newLine);
            dos.flush();
            int c = 0;
            if (httpConn.getResponseCode() == 200) {
                InputStream input = httpConn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(input, StandardCharsets.UTF_8);
                StringBuilder sb1 = new StringBuilder();
                int ss;
                while ((ss = inputStreamReader.read()) != -1) {
                    sb1.append((char) ss);
                }
                inputStreamReader.close();
                String result = sb1.toString();
                LogUtil.e(TAG, "doPostSubmitBody result: " + result);
                return sb1.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dos.close();
                baos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        LogUtil.e(TAG, "doPostSubmitBody result: " + null);
        return null;
    }

    public static String uploadClientLog(Object json) {
        UploadLogResponse uploadLogResponse = GsonUtil.fromJsonForObj(json, UploadLogResponse.class);
        File logFile = new File(FileUtils.LOG_PATH + uploadLogResponse.fileName);
        if (!logFile.exists()) {
            return NOT_FOUND;
        }
        Map<String, String> header = new HashMap<>();
        header.put("deviceNo", DeviceUtil.getDeviceSN());
        header.put("secretKey", YtdConfig.getSecretKey());
        return UplogUtils.doPostSubmitBody(uploadLogResponse.uploadUrl, header, logFile);
    }
}
